#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "cappacket.h"
#include "mainwindow.h"
#include <cmath>
#include <QDebug>
#include <QMessageBox>

#define ETH_BUFFER_LENGTH 1518

#define PI 3.1415927

QString etherPortName;

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);

CapPacket::CapPacket()
{
    m_isOK=false;
    m_iStartPoint = 0;
    m_dblSin = 0;		// 实部
    m_dblCos = 0;		// 虚部
    m_iZhouQiShu = 1;	// 采样周期数
    m_dblYouXiaoZhi = 0;	// 互感器有效值
    m_dblXW = 0;			// 互感器所示相位
    m_dblFuZhi = 11585;		// 幅值
    m_iLastSmpcnt = -1;		// 最后一个SmpCnt值
    m_iPoints = 0;			// 计算公式所包含点数
    myDB=new ProjectDB();
    m_bInitCapPara=false;
    m_iJs=0;
    m_iLost=0;
    m_bBegin=false;
    jsFlag=-1;
    //   memset(m_szl,0,sizeof(m_szl));
    iSuanFa=0;
    testType=0;
    dblMaxJg=0;
    dblMinJg=1000;
    testSelect=0;
    xieboNum=0;

    mu_sampleArray = &mu_PointArray1;
    mu_showArray = &mu_PointArray1;

    memset(channelAll_mu, 0x00, sizeof(channelAll_mu));

    memset(mu_dblYxz, 0x00, sizeof(mu_dblYxz));
    memset(mu_dblXw, 0x00, sizeof(mu_dblXw));

    memset(mu_dblSin, 0x00, sizeof(mu_dblSin));
    memset(mu_dblSin, 0x00, sizeof(mu_dblSin));

}
void CapPacket::init()
{
    rms_tmp=0;
    freq_tmp=0;
    phase_tmp=0;

    memset(m_PointArray,0,sizeof(m_PointArray));
    memset(mu_PointArray1,0,sizeof(mu_PointArray1));
    memset(mu_PointArray2,0,sizeof(mu_PointArray2));

    memset(maxSampleInChannel_tmp, 0x00, sizeof(maxSampleInChannel_tmp));

    m_iShuZiLiangMax=0;

    int i = 0;

    for(i = 0; i < 6; i++) maxInChannel[i] = 0;

    muDelayRead = 0;
}

void CapPacket::run()
{
    m_bBegin=false;
    maxSmpCnt=0;
    m_iLost=0;
    jsFlag=-1;
    CYPL=4000;

    getSysLoad();

    dblMaxJg=0;
    dblMinJg=1000;
    memset(t_MAC,0,sizeof(t_MAC));
    memset(t_cypl,0,sizeof(t_cypl));
    MuNum=0;
    m_bCapIsNoError=true;
    m_iTongDaoReal=-1;

    while(1)
    {
        if(m_bStopCap)
        {
            sleep(0.5);
            continue;
        }

        if (testType==1)
        {
            FindAll();
        }
        else if(testType == 'A')
        {
            CapMuPkt();
        }
        else if(testType == 'L')
        {
            calCompositeError();
        }
        else if(testType == 'S')
        {
            CapSZBData();
        }
        else
            CapNextPkt();
    }
}

void CapPacket::getSysLoad()
{
    QSqlQuery tbmu;
    tbmu=myDB->openWcxxforSql("select * from muinfo");
    qDebug()<<"myDB->openWcxxforSql,ok!";

    if (tbmu.next())
    {
        APPID=tbmu.value(0).toString();
        MAC=tbmu.value(1).toString();
        CYPL=tbmu.value(2).toInt();
    }
    else
    {
        APPID="";
        MAC="";
        CYPL=4000;
    }
    tbmu.clear();
}

// 设置抓包和处理数据的参数
bool CapPacket::SetCapParamater(int iTongDao, int iZhouQi, int iSmpCntStart, double dblFuZhi)
{
    m_iZhouQiShu = iZhouQi;	// 采样周期数
    m_dblFuZhi = dblFuZhi;  // 幅值
    m_iTongDao = iTongDao;  // 测量通道
    m_iZhouQi = iZhouQi;    // 周期个数
/*
    m_PointArray=(double **)malloc(sizeof(double)*m_iTongDaoCount);
    for(int i=0;i<m_iTongDaoCount;i++)
    {
        m_PointArray[i]=(double *)malloc((sizeof(double))*(m_iZhouQi * m_iSmpRate));
    }
*/
    memset(m_PointArray,0,sizeof(m_PointArray));
    memset(m_tempArray,0,sizeof(m_tempArray));

    m_iShuZiLiangMax = 0;
    m_iShuZiLiangMax_Temp = 0;
    m_iStartPoint = 0;
    m_iTestedPoints = 0;
    m_bSamplingPoints = false;
  //  m_CurrentAPDU = 0;
    m_bStopCap = false;
    m_dblFuZhi = dblFuZhi;
    return true;
}

void CapPacket::freeData()
{

    for(int i=0;i<m_iTongDaoCount;i++)
        free(m_PointArray[i]);
    free(m_PointArray);
  //  delete[] m_SmpCntArray;

/*
    for   (int i=0;i<m_iZhouQi * m_iSmpRate;i++)
    {
        delete [] m_PointArray[i];//由里至外，进行释放内存。
        m_PointArray[i]=NULL;//不要忘记，释放空间后p[i]不会自动指向NULL值，还将守在原处，只是释放内存而已，仅此而已。
    }
    delete   []m_PointArray;
    m_PointArray   =   NULL;
*/
}

// 关闭网口
bool CapPacket::Close(void)
{
    memset(szb_found, 0x00, sizeof(szb_found));
    memset(szb_delay, 0x00, sizeof(szb_delay));
    memset(maxInChannel, 0x00, sizeof(maxInChannel));

    m_bInitCapPara = false;
    m_bBegin=false;

    qDebug()<<"CapPacket::Close, goint to close the port!, m_bInitCapPara = "<< m_bInitCapPara;

//    pcap_close(m_fp);

    qDebug()<<"CapPacket::Close, close the port normorly!, m_bInitCapPara = "<< m_bInitCapPara;

    return true;
}

bool CapPacket::Open(int flag)
{
        if (flag==1)  getSysLoad();

        qDebug()<<"smv dest addr:"<<MAC;

        char errbuf[PCAP_ERRBUF_SIZE];		// 错误缓冲区

        struct pcap_pkthdr *header;
        const u_char *pkt_data;
        int res;

        m_bInitCapPara = true;

        //========================================================================
        // 打开端口
//        QString sNetPortDescription=NETDEV;
//        QByteArray ba=sNetPortDescription.toLatin1();
//        char *dev=ba.data();

        if ((m_fp = pcap_open_live(etherPortName.toLatin1().data(),BUFSIZ,1,10,errbuf)) == NULL)
        //if ((m_fp = pcap_open_live(dev,BUFSIZ,1,10,errbuf)) == NULL)
        {
            qDebug()<< "i can't open the port again!";

            m_sAnalyseResult = "端口打开失败！";
            m_bInitCapPara = false;
            return m_bInitCapPara;
        }

        pcap_setProtocolFilter(m_fp, 0x88ba);  //capture 9-2 SMV only

        int izbnum=0;

        while(1)
        {

//            if(m_bStopCap)
//            {
//                m_bInitCapPara=false;
//                return m_bInitCapPara;
//                break;
//            }

            res = pcap_next_ex(m_fp, &header, &pkt_data);
            izbnum++;

            if (izbnum>120)
                return m_bInitCapPara;

            if ((res< 1)||(header->len < 30))
            {
                m_bInitCapPara = false;
                m_sAnalyseResult = "端口打开失败！";
                m_bInitCapPara=false;
                //    return m_bInitCapPara;
            }
            else
            {
                unsigned int i, j;
                bool IsYiTaiWang;
                int ethType;//0:sv;1:goose;
                IsYiTaiWang = false;
                ethType=0;
                for(i = 0; i <= header->len && i <= YI_TAI_WANG_START_MAX; i++)
                {
                        //=======================================================
                        // 以太网标志
                        if (pkt_data[i] == 0x88 && ((pkt_data[i + 1] == 0xba) ||(pkt_data[i + 1] == 0xb8)))
                        {
                                if(i > 11)
                                {
                                        IsYiTaiWang = true;
                                        if (pkt_data[i + 1] == 0xb8)
                                            ethType=1;
                                        QString sDestination = "目的地址：", sSource = "\n源 地 址：";
                                        for(j = 0; j < 6; j++)
                                        {
                                                sDestination += getHexFormat(pkt_data[j]) + " ";
                                                sSource += getHexFormat(pkt_data[j + 6]) + " ";
                                        }
                                        m_sAnalyseResult = sDestination;
                                        m_sAnalyseResult += sSource;
                                        QString sTPID = "\nTPID：", sTCI = "  TCI：";
                                        if(i >= 14) sTPID += getHexFormat(pkt_data[12]) + " " + getHexFormat(pkt_data[13]);
                                        if(i >= 16)	sTCI += getHexFormat(pkt_data[14]) + " " + getHexFormat(pkt_data[15]);
                                        m_sAnalyseResult += sTPID;
                                        m_sAnalyseResult += sTCI;

                                        SetCapPara_92(pkt_data, header->len);

                                        break;
                                }else
                                {
                                        if(i < 11) continue;
                                }
                        }
                }
                if(IsYiTaiWang)
                {
                    QString tempAPPID=getHexFormat(pkt_data[i + 2])+getHexFormat(pkt_data[i+3]);
                    QString ma=getHexFormat(pkt_data[0]) +"-";
                    ma +=getHexFormat(pkt_data[1]) +"-";
                    ma +=getHexFormat(pkt_data[2]) +"-";
                    ma +=getHexFormat(pkt_data[3]) +"-";
                    ma +=getHexFormat(pkt_data[4]) +"-";
                    ma +=getHexFormat(pkt_data[5]);
               //     qDebug()<<ma <<" "<<tempAPPID;
                    QString  sTemp;
                    if (ethType==0)
                        m_sAnalyseResult += "\n以太网类：88 ba";
                    else if (ethType==1)
                        m_sAnalyseResult += "\n以太网类：88 b8";
                  //  QString tempAPPID=getHexFormat(pkt_data[i + 2]) +getHexFormat(pkt_data[i + 3]);
                    if (flag==1)
                    {
                        if(MAC!=ma)       return true;
                    }

                    sTemp = "  APPID：" + getHexFormat(pkt_data[i + 2]) + " " + getHexFormat(pkt_data[i + 3]);
                    m_sAnalyseResult += sTemp;
                    sTemp = "  LENGTH：";
                    int iLength = (pkt_data[i + 4] << 8) + pkt_data[i + 5];
                    sTemp += QString::number(iLength,16);
                    m_sAnalyseResult += sTemp;
                    sTemp = "\n保留1：" + getHexFormat(pkt_data[i + 6]) + " " + getHexFormat(pkt_data[i + 7]);
                    m_sAnalyseResult += sTemp;
                    sTemp = "  保留2：" + getHexFormat(pkt_data[i + 8]) + " " + getHexFormat(pkt_data[i + 9]);
                    m_sAnalyseResult +=  sTemp;

                    if (pkt_data[i + 10] == 0x80)
                    {
                        m_sAnalyseResult +=  "\nTag：80";
                        m_iAPDU_Start = i + 10;
                        SetCapPara_91(pkt_data, header->len);
                    }
                    else if(pkt_data[i + 10] == 0x60)
                    {
                        m_sAnalyseResult +=  "\nTag：60";
                        m_iAPDU_Start = i + 10;
                        SetCapPara_92(pkt_data, header->len);
                    }
                    else
                    {
                        m_sAnalyseResult +=  "\n非9-1或9-2数据！";
                        m_bInitCapPara = false;
                    }
                    m_bInitCapPara=true;
                    setJqxs();          //可去除
                    return m_bInitCapPara;
                }
                else            //IsYiTaiWang
                {
                    m_bInitCapPara = false;
                    m_sAnalyseResult = "非以太网数据！";
                    m_sGuiYueType = NotEthernet;
                    m_bInitCapPara=false;
                }
            }
        }

   //     pcap_freealldevs(alldevs);
        return m_bInitCapPara;
}
bool CapPacket::FindAll()
{
        QString m_sAPPID="";
        QString m_sMAC="";
        QString m_sType="";
      //  char errbuf[PCAP_ERRBUF_SIZE];		// 错误缓冲区
      //  pcap_if_t *alldevs;		// 可用设备列表
        struct pcap_pkthdr *header;
        const u_char *pkt_data;
                // 捕获一个数据包

            if(m_bStopCap) return true;		// 外部阻止接口
            int res = pcap_next_ex(m_fp, &header, &pkt_data);
            if ((res< 1)||(header->len < 30))
            {
                m_bInitCapPara = false;
                m_sAnalyseResult = "端口打开失败！";
                m_bInitCapPara=false;
            }
            else
            {
                unsigned int i, j;
                bool IsYiTaiWang;
                int ethType;//0:sv;1:goose;
                IsYiTaiWang = false;
                ethType=0;
                for(i = 0; i <= header->len && i <= YI_TAI_WANG_START_MAX; i++)
                {
                        if ((pkt_data[i] == 0x88) && (pkt_data[i + 1] == 0xba))
                        {
                                if(i > 11)
                                {
                                    if(i > 16) break;

                                    IsYiTaiWang = true;

                                    for(j = 0; j < 6; j++)
                                    {
                                        //    sDestination += getHexFormat(pkt_data[j]) + " ";
                                            m_sMAC +=getHexFormat(pkt_data[j]) +"-";
                                        //    sSource += getHexFormat(pkt_data[j + 6]) + " ";
                                    }
                                    m_sMAC=m_sMAC.left(m_sMAC.length()-1);

                                    //qDebug()<<m_sMAC;

                                    break;
                                }else
                                {
                                        if(i < 11) continue;
                                }
                        }
                }
                if(IsYiTaiWang)
                {
                    IsYiTaiWang = false;

                    int iSmpCnt = 0;                // 获取SmpCount值
                    m_sAPPID=getHexFormat(pkt_data[i + 2]) +getHexFormat(pkt_data[i + 3]);
                    if (pkt_data[i + 10] == 0x80)
                    {
                        m_sType="9-1";
                        m_iAPDU_Start = i + 10;
                        SetCapPara_91(pkt_data, header->len);
                    }
                    else if(pkt_data[i + 10] == 0x60)
                    {
                        m_sType="9-2";
                        m_iAPDU_Start = i + 10;
                        SetCapPara_92(pkt_data, header->len);
                    }
                    for(int j = 0; j < m_iASDU_Cnt; j++)
                    {
                        if(m_bStopCap) return true;		// 外部阻止接口
                        int iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
                        iSmpCnt = 0;
                        for(int i = 0; i < m_iSmpCnt_Length; i++)
                            iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                        if (maxSmpCnt<iSmpCnt)
                        {
                            maxSmpCnt=iSmpCnt;
                        }
                    }

                    emit sigFind(m_sAPPID,m_sMAC,m_sType,maxSmpCnt,m_iASDU_Cnt);         //显示网络列表

                    m_sAPPID = "";
                    m_sMAC = "";
                    m_sType = "";
                }
            }
    return true;
}

void CapPacket::listDevices()
{
    QString m_sAPPID="";
    QString m_sMAC="";
    QString m_sType="";

    unsigned int    appid_tmp;
    unsigned int    iSmpCnt_tmp = 0;
    unsigned char	dest_addr_tmp[6];

    struct pcap_pkthdr *header;
    const u_char *pkt_data;

    while (1)
    {
        if( testType != 1 ) break;		// stop listing

        int res = pcap_next_ex(m_fp, &header, &pkt_data);

        if ( (res < 1) || (header->len < 30) )
        {
            m_bInitCapPara = false;

            qDebug() << "CapPacket::FindAll error!";

            break;
        }
        else
        {
            unsigned int i, j;

            for(j = 0; j < 6; j++)
            {
                dest_addr_tmp[j] = pkt_data[j];
            }

            for(i = 0; i <= header->len; i++)
            {
                if ( (pkt_data[i] == 0x88) && (pkt_data[i + 1] == 0xba) ) break;
            }

            appid_tmp = pkt_data[i + 2] * 256 + pkt_data[i + 3];

            SetCapPara_92(pkt_data, header->len);

//            qDebug()<< "m_iASDU_Cnt, m_iFirstSmpCnt, mASDU_Length"<< m_iASDU_Cnt << m_iFirstSmpCnt_Start <<m_iASDU_Length;

            iSmpCnt_tmp = 0;

            for(j = 0; j < m_iASDU_Cnt; j++)
            {
                int iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);

                for(int i = 0; i < m_iSmpCnt_Length; i++)
                    iSmpCnt_tmp += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
            }

//            qDebug()<<"listDevice(), iSmpCnt_tmp="<<iSmpCnt_tmp;

            for(i = 0; i < 10; i++)
            {
                bool	dut_is_in_list = false;

                if(dut_lists[i].index > 0)
                {
                    for(j = 0; j < 6; j++) // if mac addr is matching
                    {
                        if(dut_lists[i].dst_addr[j] == dest_addr_tmp[j])
                        {
                            dut_is_in_list = true;
                        }
                        else
                        {
                            dut_is_in_list = false;
                        }
                    }

                    if(dut_is_in_list) //if appid is matching
                    {
                        if(dut_lists[i].appid != appid_tmp) dut_is_in_list = false;
                    }
                }
                else    //if dut is not in the list, and the dut_lists[i] is empty
                {
                    for(j = 0; j < 6; j++)	dut_lists[i].dst_addr[j] = dest_addr_tmp[j];
                    dut_lists[i].appid = appid_tmp;
                    dut_lists[i].index = i + 1;

                    dut_is_in_list = true;
                }
                // if a device is not in the list after the list is full, just leave it alone

                if(dut_is_in_list)
                {
                    if(dut_lists[i].smps_cnt < 5000)
                    {
                        dut_lists[i].smps_cnt++;

                        if(dut_lists[i].smp_rate < iSmpCnt_tmp) dut_lists[i].smp_rate = iSmpCnt_tmp;
                    }
                    else if(dut_lists[i].smps_cnt == 5000)	// we do nothing when smps_cnt = 5001
                    {
                        if(dut_lists[i].smp_rate > 4000)	// if smp_cnt > 4000 is found
                        {
                            dut_lists[i].smp_rate = 12800;
                        }
                        else
                        {
                            dut_lists[i].smp_rate = 4000;
                        }

                        for(j = 0; j < 6; j++)
                        {
                            m_sMAC +=getHexFormat(pkt_data[j]) +"-";
                        }

                        m_sMAC = m_sMAC.left(m_sMAC.length()-1);

                        for(j = 0; j <= header->len; j++)
                        {
                            if ( (pkt_data[j] == 0x88) && (pkt_data[j + 1] == 0xba) ) break;
                        }

                        m_sAPPID = getHexFormat(pkt_data[j + 2]) +getHexFormat(pkt_data[j + 3]);

                        m_sType = "9-2";

                        emit sigFind(m_sAPPID, m_sMAC, m_sType, dut_lists[i].smp_rate, m_iASDU_Cnt);         //show this device in the list

                        qDebug()<<"appid, maxSmpCnt, asduCnt"<<hex<<appid_tmp<<dut_lists[i].smp_rate<<m_iASDU_Cnt;

                        dut_lists[i].smps_cnt++;
                    }
                    break;
                } // if(dut_is_in_list)
            } //for(i = 0; i < 10; i++)
        } //if ( (res < 1) || (header->len < 30) )
    } // while (1)

    memset((char *)dut_lists, 0x00, sizeof(dut_lists));
}


// 清空缓冲池中的数据
void CapPacket::ClearPksPool(void)
{
        if( m_bInitCapPara )
        {
                struct pcap_pkthdr *header;	// 数据包头
                const u_char *pkt_data;		// 数据包
                int res;
                while((res = pcap_next_ex(m_fp, &header, &pkt_data) > 0))
                {

                }
        }
}

// 获得最大数字量
double CapPacket::getMaxPointValue(void)
{
        int iPoints = m_iZhouQi * m_iSmpRate;
        double dblMaxValue = 0;
        for(int i = 0; i < m_iTongDaoCount; i++)
        {
                if(m_bIsChannelShow[i])
                {
                        for(int j = 0; j < iPoints; j++)
                        {
                                if (std::abs(m_PointArray[i][j]) > dblMaxValue)
                                        dblMaxValue = std::abs(m_PointArray[i][j]);
                        }
                }
        }
        if(dblMaxValue < 1) dblMaxValue = 1;
        return dblMaxValue;
}
// 设置9-1规约的解析包参数
bool CapPacket::SetCapPara_91(const u_char* pkt_data, int pkt_len)
{
    int bbb=pkt_len;
    bbb++;
        m_sAnalyseResult = "规约类型：9-1\n" + m_sAnalyseResult;
        m_sGuiYueType = GuiYue9_1;
        m_iData_Length = 2;
        m_iTongDao_Length = 2;
        int iLoaction, iBits = 1;	// iBits为长度按ASN.1编码所占字节
        iLoaction = m_iAPDU_Start + 1;
        int iLength = 0;
        if(pkt_data[iLoaction] > 0x80)
        {
                iBits = pkt_data[iLoaction] - 0x80;
                for(int i = 1; i <= iBits; i++)
                        iLength += pkt_data[iLoaction + i] << (8 * (iBits - i));
                iLoaction += iBits;
        }else
                iLength = pkt_data[iLoaction];
        m_sAnalyseResult +=  "\nLength：" + QString::number(iLength,16);
        m_iASDU_Cnt = (pkt_data[iLoaction + 1] << 8) + pkt_data[iLoaction + 2];
        m_sAnalyseResult +=  "\nASDU数目：" + QString::number(m_iASDU_Cnt,16);
        m_iASDU_Length = (pkt_data[iLoaction + 3] << 8) + pkt_data[iLoaction + 4];
        m_sAnalyseResult +=  "  ASDU长度：" + QString::number(m_iASDU_Length,16);
        m_iASDU_Length += 2;
        m_iASDU_Start = iLoaction + 3;
        m_sAnalyseResult +=  "\n逻辑节点名：" + getHexFormat(pkt_data[m_iASDU_Start + 2]);
        m_sAnalyseResult +=  "  数据集名：" + getHexFormat(pkt_data[m_iASDU_Start + 3]);
        m_sAnalyseResult +=  "  逻辑设备名：" + getHexFormat(pkt_data[m_iASDU_Start + 4]);
        m_sAnalyseResult +=" ";
        m_sAnalyseResult += getHexFormat(pkt_data[m_iASDU_Start + 5]);

        m_sAnalyseResult +=  "\n额定相电流：" + getHexFormat((pkt_data[m_iASDU_Start + 6] >> 8)
                        + pkt_data[m_iASDU_Start + 7]);
        m_sAnalyseResult +=  "  额定零序电流：" + getHexFormat((pkt_data[m_iASDU_Start + 8] >> 8)
                        + pkt_data[m_iASDU_Start + 9]);
        m_sAnalyseResult +=  "  额定相电压：" + getHexFormat((pkt_data[m_iASDU_Start + 10] >> 8)
                        + pkt_data[m_iASDU_Start + 11]);
        m_sAnalyseResult +=  "\n额定延迟时间：" + getHexFormat((pkt_data[m_iASDU_Start + 12] >> 8)
                        + pkt_data[m_iASDU_Start + 13]);
        m_iSync_Start = 0; //9-1没有同步标志位， 所以置0
        m_iFirstData_Start = m_iASDU_Start + 14 ;
        m_iFirstSmpCnt_Start = m_iASDU_Start + 42;
        m_iSmpCnt_Length = 2;
        m_sAnalyseResult += "\n状态字1：" + getHexFormat(pkt_data[m_iASDU_Start + 38]) + " "
                        + getHexFormat(pkt_data[m_iASDU_Start + 39]);
        m_sAnalyseResult +=  "  状态字2：" + getHexFormat(pkt_data[m_iASDU_Start + 40]) + " "
                        + getHexFormat(pkt_data[m_iASDU_Start + 41]);
        m_iSmpRate = pkt_data[m_iASDU_Start + 44];
        m_sAnalyseResult +=  "\n采样速率：" + QString::number(m_iSmpRate,16);
        m_sAnalyseResult +=  "  配置版本号：" + getHexFormat(pkt_data[m_iASDU_Start + 45]);
        m_iTongDaoCount = TongDaoCount91;
        m_iTongDatCountReal = m_iTongDaoCount; //
        return true;
}

// 设置9-2规约的解析包参数
bool CapPacket::SetCapPara_92(const u_char* pkt_data, int pkt_len)
{
    int bbb=pkt_len;
    bbb++;
        m_sAnalyseResult = "规约类型：9-2LE\n"  + m_sAnalyseResult;
        m_sGuiYueType = GuiYue9_2;
        m_iData_Length = 4;
        m_iTongDao_Length = 8;
        m_iSmpRate=CYPL/50;
    //    m_iSmpRate = myDB->getSmpRate92(m_bIsStandardPort);
   //     myDB->CloseDB();
  //      m_iSmpRate=100;
        int iLocation, j, iTemp, iLen_Temp;
        QString sPartName;
        //=============================================================
        // savPdu 段
        iTemp = 0, iLen_Temp = 0;
        iLocation = m_iAPDU_Start + 1;
        if(pkt_data[iLocation] > 0x80)
        {
                iLen_Temp = pkt_data[iLocation] - 0x80;
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;		// 移动当前解析位置
        }else
                iTemp = pkt_data[iLocation];
        sPartName = "\nsavPdu：长度" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;
        //==============================================================
        // ASDU数目
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x80)
        {
                iLocation += 1;
                iLen_Temp = pkt_data[iLocation];
                m_iASDU_Cnt = 0;
                for(j = 1; j <= iLen_Temp; j++)
                        m_iASDU_Cnt += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;
        }else
                return false;
        sPartName = "\nASDU数目：" + QString::number(m_iASDU_Cnt,16);
        m_sAnalyseResult +=  sPartName;
        //==============================================================
        // ASDU序列长度
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;

        if(pkt_data[iLocation] == 0xa2)        //9-2LE
        {
                iLocation += 1;
                iTemp = pkt_data[iLocation];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        iTemp = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                }
                else
                    iLen_Temp = 0;
                iLocation += iLen_Temp;
        }
        else                 //9-2
        {
            while (1)
            {
                iLocation += 1;
                if(pkt_data[iLocation] == 0xa2)
                {
                    iLocation += 1;
                    iTemp = pkt_data[iLocation];
                    if(iTemp > 0x80)
                    {
                            iLen_Temp = iTemp - 0x80;
                            iTemp = 0;
                            for(j = 1; j <= iLen_Temp; j++)
                                    iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                    }
                    else
                        iLen_Temp = 0;
                    iLocation += iLen_Temp;
                    break;
                }
            }
        }
        sPartName = "  ASDU序列长度：" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;
        //==============================================================
        // 一个ASDU长度
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x30)
        {
                iLocation += 1;
                iTemp = pkt_data[iLocation];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        m_iASDU_Length = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                m_iASDU_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                }else
                {
                //    iLen_Temp = iTemp;
                        m_iASDU_Length = iTemp;
                }
                iLocation += iLen_Temp;
        }else
                return false;
        sPartName = "  一个ASDU长度：" + QString::number(m_iASDU_Length,16);
        m_iASDU_Length += 2;
        m_sAnalyseResult +=  sPartName;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x80)         // svID
        {
                iLocation += 1;
                iLen_Temp = pkt_data[iLocation];
                sPartName = "\nsvID：";
                for(j = 1; j <= iLen_Temp; j++)
                {
                    QString str;
                    str=QString(pkt_data[iLocation + j]);
                    sPartName +=str;
                }
                //    sPartName += QString::::Chr(pkt_data[iLocation + j]);
              //      sPartName += "a";pkt_data[iLocation + j]
                iLocation += iLen_Temp;
        }else
                return false;
        m_sAnalyseResult +=  sPartName;
        //===============================================================

        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;

        if(pkt_data[iLocation] == 0x81)         //dataset
        {
            iLocation += 1;
            iTemp = pkt_data[iLocation];
            int m_iData_Length=0;
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    for(j = 1; j <= iLen_Temp; j++)
                            m_iData_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            }else
            {
                m_iData_Length = iTemp;
            }
            iLocation += m_iData_Length;
        }
        else
            iLocation -= 1;

        iLocation += 1;
        if(pkt_data[iLocation] == 0x82)         // 采样计数
        {
                iLocation += 1;
                m_iFirstSmpCnt_Start = iLocation + 1;
                m_iSmpCnt_Length = pkt_data[iLocation];
                iLocation += m_iSmpCnt_Length;
        }else
        {

                return false;
        }
        //===============================================================        
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x83)         // 配置版本
        {
                iLocation += 1;
                iLen_Temp = pkt_data[iLocation];
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;
        }else
                return false;
        sPartName = "\n配置版本：" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x84)         //刷新时间refrTm
        {
            iLocation += 1;
            iTemp = pkt_data[iLocation];
            int m_iRef_Length=0;
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    for(j = 1; j <= iLen_Temp; j++)
                            m_iRef_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            }else
            {
                m_iRef_Length = iTemp;
            }
            iLocation += m_iRef_Length;
        }
        else
            iLocation -= 1;
        //==================================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x85)             // 采样同步
        {
                iLocation += 2;
                m_iSync_Start = iLocation;
                if(pkt_data[iLocation] == 0)
                        sPartName = "  同步状态：未同步";
                else
                        sPartName = "  同步状态：已同步";
        }else
                return false;
        m_sAnalyseResult +=  sPartName;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x86)         //采样速率smpRate
        {
            iLocation += 1;
            iTemp = pkt_data[iLocation];
            int m_ismpRate_Length=0;
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    for(j = 1; j <= iLen_Temp; j++)
                            m_ismpRate_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            }else
            {
                m_ismpRate_Length = iTemp;
            }
            iLocation += m_ismpRate_Length;
        }
        else
            iLocation -= 1;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x87)             // 数据序列
        {
                iLocation += 1;
                iTemp = pkt_data[iLocation];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        iTemp = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                        iLocation = iLocation + iLen_Temp;
                }
        }else
                return false;
        sPartName = "  数据序列：长度" + QString::number(iTemp,16);
        m_iTongDaoCount = iTemp / m_iTongDao_Length;
        m_iTongDatCountReal = m_iTongDaoCount;
        if(m_iTongDaoCount > 12) m_iTongDaoCount = 12;
        m_iFirstData_Start = iLocation + 1;			// 数据起始位置
        m_sAnalyseResult +=  sPartName;
        return true;
}

// 设置Goose规约的解析包参数
bool CapPacket::SetCapPara_Goose(const u_char* pkt_data, int pkt_len)
{
    int bbb=pkt_len;
    bbb++;
        m_sAnalyseResult = "规约类型：Goose\n"  + m_sAnalyseResult;
        m_sGuiYueType = GuiYue_Goose;
        m_iData_Length = 4;
        m_iTongDao_Length = 8;

        m_iSmpRate = 0;

        int iLocation, j, iTemp, iLen_Temp;
        QString sPartName;
        //=============================================================
        // *TL 段
        iTemp = 0, iLen_Temp = 0;
        iLocation = m_iAPDU_Start + 1;
        if(pkt_data[iLocation] > 0x80)
        {
                iLen_Temp = pkt_data[iLocation] - 0x80;
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;		// 移动当前解析位置
        }else
                iTemp = pkt_data[iLocation];
        sPartName = "\n长度:" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;

        ////////////////////////////////new
        iLocation += 1;
        if(pkt_data[iLocation] == 0x80) /////gocbRef字符串
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\ngocbRef字符串:";
            for (j=0;j<iLen_Temp;j++)
            {
                iLocation++;
             //   sPartName+=getHexFormat(pkt_data[iLocation]);
                sPartName+= (pkt_data[iLocation] & 0xFF);
            }
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x81) /////有效时间t
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int yxsj_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    yxsj_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName="\n有效时间t(ms):" + QString::number(yxsj_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x82) /////DatSet字符串
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nDatSet字符串:";
            for (j=0;j<iLen_Temp;j++)
            {
                iLocation+=1;
                sPartName+=(pkt_data[iLocation] & 0xFF);
            }
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x83) /////GoID字符串
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nGoID字符串:";
            for (j=0;j<iLen_Temp;j++)
            {
                iLocation+=1;
                sPartName+=(pkt_data[iLocation] & 0xFF);
            }
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x84) /////StNum
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            double st_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    st_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nStNum+1的时间t(ms):" + QString::number(st_tmp);
            m_sAnalyseResult +=  sPartName;
            iLocation += iLen_Temp;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x85) /////变化序列号
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int xlh_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    xlh_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nStNum:" + QString::number(xlh_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x86) /////报文顺序号
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int xlh_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    xlh_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nSqNum:" + QString::number(xlh_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x87) /////测试标志
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nTest:";
            iLocation+=1;
            if (pkt_data[iLocation]==0x01)
                sPartName+="TRUE";
            else
                sPartName+="FALSE";
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x88) /////配置版本号
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int xlh_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    xlh_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nconfRev:" + QString::number(xlh_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x89) /////未配置好标志
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nndsCom:";
            iLocation+=1;

            if (pkt_data[iLocation]==0x01)
                sPartName+="TRUE";
            else
                sPartName+="FALSE";
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x8a) /////Goose单元个数
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            int gs_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    gs_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\n总个数:" + QString::number(gs_tmp);
            m_sAnalyseResult +=  sPartName;
            iLocation += iLen_Temp;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0xab) /////Goose单元数据
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
         //   double gs_tmp=0;
         //   for(j = 1; j <= iLen_Temp; j++)
         //           gs_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\n长度:" + QString::number(iLen_Temp);
            m_sAnalyseResult +=  sPartName;
            iLocation += iLen_Temp;
        }
        //===========new
        //==============================================================
qDebug()<<m_sAnalyseResult;
        return true;
}
void CapPacket::setJqxs()
{
    int t=6;
    int num=m_iSmpRate;
    int N=num*t;
    int L=5*4*3*2*1;
    for(int m=0;m<N;m++)
    {
        ti[m]=(double)t*(m-(N+1)/2)/N;
        if (ti[m]<0)
            ti[m] *=-1;
        if(ti[m]>3|| ti[m]==3)
            ti[m]=0;
        else if((ti[m]>2 || ti[m]==2) && ti[m]<3)
          //  ti[m]=((3-ti[m])^5)/L;
            ti[m]=std::pow((3-ti[m]),5)/L;
        else if((ti[m]>1 || ti[m]==1) && ti[m]<2)
            ti[m]=std::pow((3-ti[m]),5)/L
                  -std::pow((2-ti[m]),5)*6/L;
        else
            ti[m]=std::pow((1-ti[m]),5)*9/L
                  -std::pow((2-ti[m]),5)*2/L
                  -std::pow(ti[m],5)*4/L
                  +std::pow((1+ti[m]),5)/L
                  +(1-ti[m]);
    }
}

// 捕获下一个包
bool CapPacket::CapNextPkt(void)
{
    if(m_bInitCapPara) // if the interface is opened properly
    {
        struct pcap_pkthdr *header;	// 数据包头
        const u_char *pkt_data;		// 数据包
        int iData_Start;			// 数据位起始位
        int iSmpCnt_Start;			// SmpCount起始位
        int iSmpCnt;				// SmpCount值
        int iShuZiLiang;			// 数字量
        int res;
        if (m_iSmpRate<=0)
            m_iSmpRate=CYPL/50;
        if((res = pcap_next_ex(m_fp, &header, &pkt_data)) > 0)
        {                               // 符合规约标准
            if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
            {
                    for(int j = 0; j < m_iASDU_Cnt; j++)
                    {
                        if(m_bStopCap) return true;		// 外部阻止接口
                        int i;

                        iSmpCnt = 0;                // 获取SmpCount值
                        iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
                        for(i = 0; i < m_iSmpCnt_Length; i++)
                            iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );

                //          qDebug()<<iSmpCnt;
                        m_Sync = pkt_data[m_iSync_Start];       //采样同步标志（仅对9-2有效）                        

                        if(m_iTongDao != TestChannel_PinLv)		// 状态为报文检验，无须分析数字量
                        {
                            if(! m_bSamplingPoints && iSmpCnt == m_iStartPoint)
                            {
                                m_bSamplingPoints = true;
                                m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                m_iShuZiLiangMax_Temp = 0;
                                m_iTestedPoints = 0;
                                m_bCapIsNoError = true;
                             //   parent->jsWc(); //计算误差
                                emit sigJswc();
                            }
                            if(m_bSamplingPoints)
                            {
                                int nLBound = m_iTongDao / m_iTongDaoCount * m_iTongDaoCount;	// 起始通道
                                qDebug()<<"CapNextPkt(), nLBound"<<nLBound;
                                for (int k = 0; k < m_iTongDaoCount && (k + nLBound) < m_iTongDatCountReal; k++)
                                {
                                    int kk = k + nLBound;	// 真实通道序号

                                    iShuZiLiang = 0;

                                    iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * kk;

                                    for(i = 0; i < m_iData_Length; i++)
                                        iShuZiLiang += (pkt_data[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );

                                    if(m_sGuiYueType == GuiYue9_1 && iShuZiLiang >= 0x8000 && iShuZiLiang <= 0xFFFF)
                                        iShuZiLiang += 0xFFFF0000;

                                    if(m_bIsChannelShow[k])		// 计算可视通道的最大值
                                    {
                                        int iTemp = std::fabs(iShuZiLiang);
                                        if(iTemp > m_iShuZiLiangMax_Temp)
                                            m_iShuZiLiangMax_Temp = iTemp;

                                        if(iTemp > maxSampleInChannel_tmp[k]) maxSampleInChannel_tmp[k] = iTemp;

                                        m_PointArray[k][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                                    }
                                    if (kk==m_iTongDao)
                                    {
                                        m_iTongDaoReal=kk;

                                        if (testSelect==1)   //谐波测量时
                                        {
                                            m_dblSin += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * xieboNum * m_iTestedPoints / m_iSmpRate);
                                            m_dblCos += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * xieboNum * m_iTestedPoints / m_iSmpRate);
                                        }
                                        else
                                        {
                                            m_dblSin += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * m_iTestedPoints / m_iSmpRate);
                                            m_dblCos += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * m_iTestedPoints / m_iSmpRate);
                                        }
                                   //     m_szl[m_iTestedPoints]=iShuZiLiang;

                                    }
                                    if(m_bStopCap) return true;		// 外部停止接口
                                }
                                if(m_iTestedPoints < m_iZhouQi * m_iSmpRate - 1)
                                {
                                    if (m_iTestedPoints!=iSmpCnt)
                                        m_bCapIsNoError=false;
                                //    qDebug()<<m_iTestedPoints<<" "<<iSmpCnt;
                                    m_iTestedPoints++;
                                    if(m_iTongDao==TestChannel_LuBo)
                                        pcap_dump((unsigned char*)dumpfile,header,pkt_data); //写入
                                }
                                else
                                {
                                    if ((!m_bCapIsNoError) &&(testSelect==0))   //谐波测量时除外
                                    {
                                        m_bSamplingPoints = false;
                                        m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                        m_dblSin=0;
                                        m_dblCos=0;
                                        return true;
                                    }
                                    if(m_iTongDao==TestChannel_LuBo)
                                    {
                                        pcap_dump((unsigned char*)dumpfile,header,pkt_data); //写入
                                        pcap_dump_close(dumpfile);   //关闭

                                        StopCap(true);
                                    }
                                    else
                                    {
                                        memcpy(m_tempArray,m_PointArray,sizeof(m_tempArray));
                                        memset( m_PointArray, 0x00, sizeof(m_PointArray));

                                        memcpy(maxSampleInChannel, maxSampleInChannel_tmp, sizeof(maxSampleInChannel));
                                        memset(maxSampleInChannel_tmp, 0x00, sizeof(maxSampleInChannel_tmp));

                                        if (iSuanFa==0)
                                        {
                                            m_dblYouXiaoZhi = std::sqrt(m_dblSin * m_dblSin + m_dblCos * m_dblCos) * 1000
                                                                        / std::sqrt(2) / m_dblFuZhi / (double)m_iZhouQiShu;
                                            m_dblXW = GetXiangJiao(m_dblSin, m_dblCos) * 60;
                                        }
                                        else if (iSuanFa==1)
                                        {
                                            /*
                                            int num=m_iSmpRate;
                                            int N=num*6;
                                            double vol=0;
                                            for (int m=0;m<N;m++)
                                                vol=vol+ti[m]*m_szl[m]*m_szl[m];
                                            m_dblYouXiaoZhi=std::sqrt(vol/num) / m_dblFuZhi ;
                                            m_dblXW = GetXiangJiao(m_dblSin, m_dblCos) * 60;
                                            */
                                        }
                                        else if (iSuanFa==2)
                                        {
                                        //    harmonic(m_szl,1,m_iSmpRate*10,m_iSmpRate*50);
                                            dft_14(m_tempArray[m_iTongDaoReal],1,m_iSmpRate*10,m_iSmpRate*50);   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
                                        }
                                    }

                                    m_bSamplingPoints = false;
                                    m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                    m_dblSin=0;
                                    m_dblCos=0;

                                    emit sigCyOver();
                                    setIsOK(true);

                                    return true;		// 经过一次成功的采集
                                }
                            }
                        }
                        else      // 状态为报文检验，无须分析数字量 主要为报文校验
                        {
                            if (jsFlag==-1)
                            {
                                jsFlag=0;
                                m_iJs=0;
                                m_iJs=iSmpCnt;
                            }
                            else
                            {
                                endm=header->ts.tv_usec;
                              //  qDebug()<<endm;
                                double timeuse=endm-startm;
                                if(timeuse<0)
                                    timeuse +=1000000;
                              //  qDebug()<<iSmpCnt<<" "<<header->ts.tv_sec<<"."<<header->ts.tv_usec;
                                if (m_iType==1)
                                {
                                    if (timeuse>dblMaxJg)
                                        dblMaxJg=timeuse;
                                    if (timeuse<dblMinJg)
                                        dblMinJg=timeuse;
                                }
                                else
                                {                                    
                                    m_iJs++;
                                    if (iSmpCnt==0)
                                        m_iJs=0;
                                    int iCnt=m_iJs-iSmpCnt;
                                    if (iCnt>0)
                                    {
                                        iCnt= m_iSmpRate * 50 - m_iJs + iSmpCnt;
                                        if (iCnt<0)
                                        {
                                            iCnt= 65536 - m_iJs + iSmpCnt;
                                        }
                                        m_iLost+=iCnt;
                                        m_iJs=iSmpCnt;
                                    }
                                    else if (iCnt<0)
                                    {
                                        m_iLost+=std::abs(iCnt);
                                        m_iJs=iSmpCnt;
                                    }
                                }
                            }
                            startm=header->ts.tv_usec;
                            m_iTestedPoints++;
                            if(m_iTestedPoints >= m_iZhouQi * m_iSmpRate - 1)       //m_iZhouQi个周期结束
                            {
                                m_iTestedPoints=0;
                            }

                        }          //
                    }
               // }
            }
        }
    }
    return false;
}

QString CapPacket::getHexFormat(int iValue)
{
        QString sRes;
     //   sRes = iValue.ToString("X");
        sRes=QString::number(iValue,16);
        if(iValue < 0x10)
                sRes = "0" + sRes;
        return sRes;
}

void CapPacket::pcap_lubo()
{
    QDateTime time = QDateTime::currentDateTime();

    QString str = time.toString("yyyy-MM-dd-hh-mm-ss");

    QString filename = str + ".pcap";

    QDir toDir= QDir("c://model-2000/");

    if(toDir.exists("pcap"))
    {
        qDebug() << "/pcap/ is existed!";

        toDir.setPath("c://model-2000/pcap");
        toDir.setFilter(QDir::Files);
        toDir.setSorting(QDir::Time);

        QFileInfoList list = toDir.entryInfoList();

        int i = 0;
        for(i=0 ; i<list.size(); i++)
        {
            if(i > 20)
            {
                QFileInfo fileInfo = list.at(i);
                toDir.remove( fileInfo.fileName() );

                qDebug() << "Deleted file: "<<fileInfo.fileName();
            }
        }
    }
    else
    {
        qDebug() << "mkdir pcap";
        toDir.mkdir("pcap");
        toDir.setPath("c://model-2000/pcap");
    }

    filename = toDir.absolutePath()+ "/" + filename;
    QByteArray ba = filename.toLatin1();
    char *fname = ba.data();
    dumpfile = pcap_dump_open(m_fp, fname);
}

void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
 /* 此函数功能将数据报存储到堆文件 */
 pcap_dump(dumpfile, header, pkt_data);
}
void CapPacket::pcap_stopLubo()
{
    if (m_fp > 0)
        pcap_breakloop(m_fp);
}
void CapPacket::pcap_openFile(QString sfile)
{
    pcap_t *fd;
    char *err;
    int res;
    int icypl=0;
    int iData_Start;			// 数据位起始位
    int iSmpCnt_Start;			// SmpCount起始位
    int iSmpCnt;			// SmpCount值
    int iShuZiLiang;			// 数字量
    bool bInit=true;
    int iZhouQi=0;
    QByteArray ba = sfile.toLatin1();
    const char *file=ba.data();
    fd=pcap_open_offline(file,err);
    pcap_pkthdr * header;
    const u_char *pkt_data;

    while(1)
    {
        res=pcap_next_ex(fd,&header,&pkt_data);
        if ((res< 1)||(header->len < 30))
        {
            m_sAnalyseResult = "端口打开失败！";
            break;
        }
        else
        {
            unsigned int i, j;
            bool IsYiTaiWang;
            int ethType;//0:sv;1:goose;
            IsYiTaiWang = false;
            ethType=0;
            for(i = 0; i <= header->len && i <= YI_TAI_WANG_START_MAX; i++)
            {
                    //=======================================================
                    // 以太网标志
                    if (pkt_data[i] == 0x88 && ((pkt_data[i + 1] == 0xba) ||(pkt_data[i + 1] == 0xb8)))
                    {
                            if(i > 11)
                            {
                                    IsYiTaiWang = true;
                                    if (pkt_data[i + 1] == 0xb8)
                                        ethType=1;
                                    QString sDestination = "目的地址：", sSource = "\n源 地 址：";
                                    for(j = 0; j < 6; j++)
                                    {
                                            sDestination += getHexFormat(pkt_data[j]) + " ";
                                            sSource += getHexFormat(pkt_data[j + 6]) + " ";
                                    }
                                    m_sAnalyseResult = sDestination;
                                    m_sAnalyseResult += sSource;
                                    QString sTPID = "\nTPID：", sTCI = "  TCI：";
                                    if(i >= 14) sTPID += getHexFormat(pkt_data[12]) + " " + getHexFormat(pkt_data[13]);
                                    if(i >= 16)	sTCI += getHexFormat(pkt_data[14]) + " " + getHexFormat(pkt_data[15]);
                                    m_sAnalyseResult += sTPID;
                                    m_sAnalyseResult += sTCI;
                                    break;
                            }else
                            {
                                    if(i < 11) continue;
                            }
                    }
            }
            if(IsYiTaiWang)
            {
                QString  sTemp;
                if (ethType==0)
                    m_sAnalyseResult += "\n以太网类：88 ba";
                else if (ethType==1)
                    m_sAnalyseResult += "\n以太网类：88 b8";

                        sTemp = "  APPID：" + getHexFormat(pkt_data[i + 2]) + " " + getHexFormat(pkt_data[i + 3]);
                        m_sAnalyseResult += sTemp;
                        sTemp = "  LENGTH：";
                        int iLength = (pkt_data[i + 4] << 8) + pkt_data[i + 5];
                        sTemp += QString::number(iLength,16);
                        m_sAnalyseResult += sTemp;
                        sTemp = "\n保留1：" + getHexFormat(pkt_data[i + 6]) + " " + getHexFormat(pkt_data[i + 7]);
                        m_sAnalyseResult += sTemp;
                        sTemp = "  保留2：" + getHexFormat(pkt_data[i + 8]) + " " + getHexFormat(pkt_data[i + 9]);
                        m_sAnalyseResult +=  sTemp;
                        if (pkt_data[i + 10] == 0x80)
                        {
                            m_sAnalyseResult +=  "\nTag：80";
                            m_iAPDU_Start = i + 10;
                            SetCapPara_91(pkt_data, header->len);
                        }
                        else if(pkt_data[i + 10] == 0x60)
                        {
                            m_sAnalyseResult +=  "\nTag：60";
                            m_iAPDU_Start = i + 10;
                            SetCapPara_92(pkt_data, header->len);
                        }
                        else
                        {
                            m_sAnalyseResult +=  "\n非9-1或9-2数据！";
                            bInit = false;
                        }
                        break;
            }
            else            //IsYiTaiWang
            {
                bInit = false;
                m_sAnalyseResult = "非以太网数据！";
                m_sGuiYueType = NotEthernet;
            }
        }
    }
    if (bInit)
    {
        fd=pcap_open_offline(file,err);
        while(1)
        {
            res=pcap_next_ex(fd,&header,&pkt_data);
            if ((res< 1)||(header->len < 30))
            {
                break;
            }
            if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
            {
                for(int j = 0; j < m_iASDU_Cnt; j++)
                {
                    int i;
                    iSmpCnt = 0;                // 获取SmpCount值
                    iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
                    for(i = 0; i < m_iSmpCnt_Length; i++)
                        iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                    if (iSmpCnt>icypl)
                        icypl=iSmpCnt;
                    if (iSmpCnt==0)
                        iZhouQi++;
                }
            }
        }
        if (icypl>12700)
            icypl=12800;
        else if (icypl>3990)
            icypl=4000;
        m_iSmpRate=icypl/50;
        fd=pcap_open_offline(file,err);
        m_iShuZiLiangMax_Temp = 0;
        while(1)
        {
            res=pcap_next_ex(fd,&header,&pkt_data);
            if ((res< 1)||(header->len < 30))
            {
                m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                emit sigCyOver();
                break;
            }
            if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
            {
        for(int j = 0; j < m_iASDU_Cnt; j++)
        {
            int i;
            iSmpCnt = 0;                // 获取SmpCount值
            iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
            for(i = 0; i < m_iSmpCnt_Length; i++)
                iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
            m_Sync = pkt_data[m_iSync_Start];       //采样同步标志（仅对9-2有效）

                if(! m_bSamplingPoints && iSmpCnt == m_iStartPoint)
                {
                    m_bSamplingPoints = true;


                    m_iTestedPoints = 0;
                }
                if(m_bSamplingPoints)
                {
                  int nLBound =0;//  int nLBound = m_iTongDao / m_iTongDaoCount * m_iTongDaoCount;	// 起始通道
                    for (int k = 0; k < 12; k++)
                    {
                        int kk = k + nLBound;	// 真实通道序号
                        iShuZiLiang = 0;
                        iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * kk;
                        for(i = 0; i < m_iData_Length; i++)
                            iShuZiLiang += (pkt_data[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                        if(m_sGuiYueType == GuiYue9_1 && iShuZiLiang >= 0x8000 && iShuZiLiang <= 0xFFFF)
                        iShuZiLiang += 0xFFFF0000;
                        if(m_bIsChannelShow[k])		// 计算可视通道的最大值
                        {
                            int iTemp = std::fabs(iShuZiLiang);
                            if(iTemp > m_iShuZiLiangMax_Temp)
                                m_iShuZiLiangMax_Temp = iTemp;
                       //     qDebug()<<k<<" "<<m_iTestedPoints<<" "<<iShuZiLiang;
                            m_PointArray[k][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                        }
                    }
                    if(m_iTestedPoints < iZhouQi * 50 * m_iSmpRate - 1)
                    {
                        m_iTestedPoints++;
                    }
                    else
                    {
                        m_bSamplingPoints = false;
                    }
                }
            }
    }
        }
    }
}

void CapPacket::pcap_setProtocolFilter(pcap_t* ethSocket, unsigned short etherType)
{
    char filterString[100];

    struct bpf_program etherTypeFilter;

    sprintf(filterString, "(ether proto 0x%04x) or (vlan and ether proto 0x%04x)", etherType, etherType);

    if (pcap_compile(ethSocket, &etherTypeFilter, filterString, 1, 0) < 0) {
        qDebug()<< "Compiling packet filter failed!";
        return;
    }

    if (pcap_setfilter(ethSocket, &etherTypeFilter) < 0) {
        qDebug()<< "Setting packet filter failed!";
    }
    else
    {
        qDebug()<< "Setting packet filter Succeed!";
    }
}

void CapPacket::CapMuPkt()
{
    struct pcap_pkthdr *header;	// 数据包头
    const u_char *pkt_data;		// 数据包
    int packetSize;

    u_char buff[ETH_BUFFER_LENGTH] = {0};

    int iData_Start = 0;			// 数据位起始位
    int iSmpCnt_Start = 0;			// SmpCount起始位
    int iSmpCnt = 0;				// SmpCount值
    double iShuZiLiang = 0;			// 数字量

    static int m_iTestedPoints_a = 0;
    static int m_iTestedPoints_b = 0;
    static int m_iTestedPoints_c = 0;

    static double maxInChannel_tmp[24]={0};

    /*
     * CYPL
     * m_iASDU_Cnt
     * m_iFirstSmpCnt_Start
     * m_iASDU_Length
     * m_iSmpCnt_Length
     *
     */

    if( (m_iSmpRate = CYPL/50) == 0)
    {
        qDebug()<<"CapPacket:SmpRate error";
        return;
    }

    if(m_bInitCapPara) // if the interface is opened properly
    {        
        int pcapCode = pcap_next_ex(m_fp, &header, &pkt_data);

        if (pcapCode > 0) {

                packetSize = header->caplen;

                if (packetSize > ETH_BUFFER_LENGTH)
                {
                        packetSize = ETH_BUFFER_LENGTH;
                }

                memcpy(buff, pkt_data, packetSize);
        }
        else
        {
            //qDebug()<< "CapMuPkt(), cap packet error!";
            return;
        }

        if(packetSize > 0)
        {
            for(int j = 0; j < m_iASDU_Cnt; j++)
            {
                if(m_bStopCap) return;

                iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);

                for(int i = 0; i < m_iSmpCnt_Length; i++)
                {
                    iSmpCnt += (buff[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                }

                if(! UnSyncMod)
                {
                    if(iSmpCnt == 0)
                    {
                        m_iTestedPoints = 0;

                        m_iTestedPoints_a = 0;
                        samplesIsReady[0] = false;

                        m_iTestedPoints_b = 0;
                        samplesIsReady[1] = false;

                        m_iTestedPoints_c = 0;
                        samplesIsReady[2] = false;

    //                    qDebug()<<"CapPacket: reset samplesIsReady_c, smpCnt="<<iSmpCnt;
                    }

                    if(iSmpCnt == 0)
                    {
                        // do caculation when udp is ready
                        //QTimer::singleShot(500, this, SLOT( capacketIsReady()) );

                        emit sigCyOver();
                        emit sigJsMutwc();
                    }
                }
                else
                {
                    double time_stamp = 0;

                    for(int i=0;i<4;i++)
                         time_stamp += (buff[packetSize - i - 1] << (8 * i) );
                    time_stamp = (time_stamp * 40)/1000;

                    if( time_stamp < 250 )
                    {
                        time_stamp_mini = time_stamp;

                        m_iTestedPoints = 0;

                        m_iTestedPoints_a = 0;
                        samplesIsReady[0] = false;

                        m_iTestedPoints_b = 0;
                        samplesIsReady[1] = false;

                        m_iTestedPoints_c = 0;
                        samplesIsReady[2] = false;

                        emit sigJsMutwc(); // do caculation at the begin of next second
                        emit sigCyOver();
                    }

                    muDelayRead = 0;

                    if(muDelayGived == 0) //If gived , don't read
                    {
                        for(int i=0;i<4;i++)
                           muDelayRead += (buff[m_iFirstData_Start + i] << (8 * (4 - i -1)) );
                    }

                    // qDebug()<<"time_stamp"<<time_stamp<<iSmpCnt;
                }

                m_Sync = buff[m_iSync_Start];

                for (int k = 0; k < m_iTongDatCountReal ; k++)
                {

                    iShuZiLiang = 0.00000000000001;

                    iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * k;


                    for(int i = 0; i < m_iData_Length; i++) // rebuild the data to int according to m_iData_Length
                    {
                        iShuZiLiang += (buff[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                    }

                    if((!samplesIsReady[0]) && ( k == channelAll_mu[0])) // if phase a is not ready
                    {
//                        mu_dblSin[0] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * (m_iTestedPoints_a%m_iSmpRate) / m_iSmpRate);
//                        mu_dblCos[0] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * (m_iTestedPoints_a%m_iSmpRate) / m_iSmpRate);


                        mu_dblSin[0] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /100) * std::sin(2 * PI * m_iTestedPoints_a / m_iSmpRate);
                        mu_dblCos[0] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /100) * std::cos(2 * PI * m_iTestedPoints_a / m_iSmpRate);

//                        qDebug()<<"CapPacket: Ua, found samples "<<mu_dblSin[0]<<m_iTestedPoints_a;

                        (*mu_sampleArray)[0][m_iTestedPoints] = iShuZiLiang/100.0;// 存储绘图所需数字量数组
                    }
                    else if((!samplesIsReady[0]) && (k == channelAll_mu[3]))
                    {
                        mu_dblSin[3] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * m_iTestedPoints_a / m_iSmpRate);
                        mu_dblCos[3] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * m_iTestedPoints_a / m_iSmpRate);

                        (*mu_sampleArray)[3][m_iTestedPoints] = iShuZiLiang/1000.0;// 存储绘图所需数字量数组
                    }

                    if((!samplesIsReady[1]) && ( k == channelAll_mu[1])) // if phase b is not ready
                    {
//                        qDebug()<<"CapPacket: Ub, found samples ["<<iShuZiLiang<<"],       smpCnt="<<iSmpCnt;
                        mu_dblSin[1] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /100) * std::sin(2 * PI * m_iTestedPoints_b / m_iSmpRate);
                        mu_dblCos[1] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /100) * std::cos(2 * PI * m_iTestedPoints_b / m_iSmpRate);
                        (*mu_sampleArray)[1][m_iTestedPoints] = iShuZiLiang/100.0;// 存储绘图所需数字量数组
                    }
                    else if((!samplesIsReady[1]) && (k == channelAll_mu[4]))
                    {
                        mu_dblSin[4] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * m_iTestedPoints_b / m_iSmpRate);
                        mu_dblCos[4] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * m_iTestedPoints_b / m_iSmpRate);

                        (*mu_sampleArray)[4][m_iTestedPoints] = iShuZiLiang/1000.0;// 存储绘图所需数字量数组
                    }

                    if((!samplesIsReady[2]) && ( k == channelAll_mu[2])) // if phase c is not ready
                    {
//                        qDebug()<<"CapPacket: Uc, found samples ["<<iShuZiLiang<<"],       smpCnt="<<iSmpCnt;
                        mu_dblSin[2] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /100) * std::sin(2 * PI * m_iTestedPoints_c / m_iSmpRate);
                        mu_dblCos[2] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /100) * std::cos(2 * PI * m_iTestedPoints_c / m_iSmpRate);

                        (*mu_sampleArray)[2][m_iTestedPoints] = iShuZiLiang/100.0;// 存储绘图所需数字量数组
                    }
                    else if((!samplesIsReady[2]) && (k == channelAll_mu[5]))
                    {
                        mu_dblSin[5] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * m_iTestedPoints_c / m_iSmpRate);
                        mu_dblCos[5] += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * m_iTestedPoints_c / m_iSmpRate);

                        (*mu_sampleArray)[5][m_iTestedPoints] = iShuZiLiang/1000.0;// 存储绘图所需数字量数组
                    }

                    int channel_num = 0;
                    for(;channel_num < 6; channel_num ++)
                    {
                        if( k == channelAll_mu[channel_num] )   // if the channel is mapped to phaseA,phaseB,phaseC
                        {
                            int iTemp = std::fabs(iShuZiLiang);

                            if(iTemp > maxInChannel_tmp[k])
                                maxInChannel_tmp[k] = iTemp;
                        }
                    }

                    if(m_bStopCap) return;		// 外部停止接口
                }

                if(m_iTestedPoints < 10 * m_iSmpRate - 1) // do drawing every ten cycles
                {
                    m_iTestedPoints++;
                }
                else if(m_iTestedPoints == 10 * m_iSmpRate - 1)
                {
                    if(mu_sampleArray == &mu_PointArray1)
                    {
                        mu_sampleArray = &mu_PointArray2;
                        mu_showArray = &mu_PointArray1;
                    }
                    else
                    {
                        mu_sampleArray = &mu_PointArray1;
                        mu_showArray = &mu_PointArray2;
                    }

                    m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                    m_iShuZiLiangMax_Temp = 0;

                    int iChannel;
                    for(iChannel = 0; iChannel < 6; iChannel++)
                    {
                        int channel = channelAll_mu[iChannel];

                        if(maxInChannel_tmp[channel] > maxValueMu[iChannel])
                            maxInChannel[iChannel] = maxInChannel_tmp[channel];
                        else
                            maxInChannel[iChannel] = maxValueMu[iChannel];

                        maxInChannel_tmp[channel] = 0;
                    }

                    m_iTestedPoints++;
                }

                if(m_iTestedPoints_a < 10 * m_iSmpRate - 1)
                {
                    m_iTestedPoints_a ++;
                }
                else if(!samplesIsReady[0]) // if data for phase a is ready, process the data & change the flag to true
                {
#if 0
                    mu_dblYxz[0] = std::sqrt(mu_dblSin[0] * mu_dblSin[0] + mu_dblCos[0] * mu_dblCos[0]) * 10
                            / std::sqrt(2) / maxValueMu[0];

                    mu_dblXw[0] = GetXiangJiao(mu_dblSin[0], mu_dblCos[0]) * 60;
#else
                    dft_14((*mu_showArray)[0], 1, 800, 4000);

                    mu_dblYxz[0] = 100.0 * rms_tmp / maxValueMu[0];
                    mu_dblXw[0] = phase_tmp;
#endif
                    mu_dblSin[0] = 0;
                    mu_dblCos[0] = 0;
#if 0
                    mu_dblYxz[3] = std::sqrt(mu_dblSin[3] * mu_dblSin[3] + mu_dblCos[3] * mu_dblCos[3]) * 10
                            / std::sqrt(2) / maxValueMu[3];

                    mu_dblXw[3] = GetXiangJiao(mu_dblSin[3], mu_dblCos[3]) * 60;
#else
                    dft_14((*mu_showArray)[3], 1, 800, 4000);

                    mu_dblYxz[3] = 100.0 * rms_tmp / maxValueMu[3];
                    mu_dblXw[3] = phase_tmp;
#endif
                    mu_dblSin[3] = 0;
                    mu_dblCos[3] = 0;

                    samplesIsReady[0] = true;

                    m_iTestedPoints_a = 0;

                    qDebug()<<"CapPacket: data for phase a is ready...Ua="<<mu_dblYxz[0]<<",Ua_xw="<<mu_dblXw[0];
                    qDebug()<<"CapPacket: data for phase a is ready...Ia="<<mu_dblYxz[3]<<",Ia_xw="<<mu_dblXw[3];
                }

                if(m_iTestedPoints_b < 10 * m_iSmpRate- 1)
                {
                    m_iTestedPoints_b ++;
                }
                else if(!samplesIsReady[1]) // if data for phase b is ready, process the data & change the flag to true
                {
#if 0
                    mu_dblYxz[1] = std::sqrt(mu_dblSin[1] * mu_dblSin[1] + mu_dblCos[1] * mu_dblCos[1]) * 10
                            / std::sqrt(2) /maxValueMu[1];

                    mu_dblXw[1] = GetXiangJiao(mu_dblSin[1], mu_dblCos[1]) * 60;
#else
                    dft_14((*mu_showArray)[1], 1, 800, 4000);

                    mu_dblYxz[1] = 100.0 * rms_tmp / maxValueMu[1];
                    mu_dblXw[1] = phase_tmp;
#endif
                    mu_dblSin[1] = 0;
                    mu_dblCos[1] = 0;

#if 0
                    mu_dblYxz[4] = std::sqrt(mu_dblSin[4] * mu_dblSin[4] + mu_dblCos[4] * mu_dblCos[4]) * 10
                            / std::sqrt(2) /maxValueMu[4];

                    mu_dblXw[4] = GetXiangJiao(mu_dblSin[4], mu_dblCos[4]) * 60;
#else
                    dft_14((*mu_showArray)[4], 1, 800, 4000);

                    mu_dblYxz[4] = 100.0 * rms_tmp / maxValueMu[4];
                    mu_dblXw[4] = phase_tmp;
#endif
                    mu_dblSin[4] = 0;
                    mu_dblCos[4] = 0;

                    samplesIsReady[1] = true;

                    m_iTestedPoints_b = 0;

                    qDebug()<<"CapPacket: data for phase b is ready...Ub="<<mu_dblYxz[1]<<",Ub_xw="<<mu_dblXw[1];
                    qDebug()<<"CapPacket: data for phase b is ready...Ib="<<mu_dblYxz[4]<<",Ib_xw="<<mu_dblXw[4];
                }

                if(m_iTestedPoints_c < 10 * m_iSmpRate- 1)
                {
                    m_iTestedPoints_c ++;
                }
                else if(!samplesIsReady[2]) // if data for phase c is ready, process the data & change the flag to true
                {
#if 0
                    mu_dblYxz[2] = std::sqrt(mu_dblSin[2] * mu_dblSin[2] + mu_dblCos[2] * mu_dblCos[2]) * 10
                            / std::sqrt(2) /maxValueMu[2];

                    mu_dblXw[2] = GetXiangJiao(mu_dblSin[2], mu_dblCos[2]) * 60;
#else
                    dft_14((*mu_showArray)[2], 1, 800, 4000);

                    mu_dblYxz[2] = 100.0 * rms_tmp / maxValueMu[2];
                    mu_dblXw[2] = phase_tmp;
#endif
                    mu_dblSin[2] = 0;
                    mu_dblCos[2] = 0;

#if 0
                    mu_dblYxz[5] = std::sqrt(mu_dblSin[5] * mu_dblSin[5] + mu_dblCos[5] * mu_dblCos[5]) * 10
                            / std::sqrt(2) /maxValueMu[5];

                    mu_dblXw[5] = GetXiangJiao(mu_dblSin[5], mu_dblCos[5]) * 60;
#else
                    dft_14((*mu_showArray)[5], 1, 800, 4000);

                    mu_dblYxz[5] = 100.0 * rms_tmp / maxValueMu[5];
                    mu_dblXw[5] = phase_tmp;
#endif
                    mu_dblSin[5] = 0;
                    mu_dblCos[5] = 0;

                    samplesIsReady[2] = true;

                    m_iTestedPoints_c = 0;

                    qDebug()<<"CapPacket: data for phase c is ready...Uc="<<mu_dblYxz[2]<<",Uc_xw="<<mu_dblXw[2];
                    qDebug()<<"CapPacket: data for phase c is ready...Ic="<<mu_dblYxz[5]<<",Ic_xw="<<mu_dblXw[5];

                    qDebug()<<"CapPacket:: all data is ready...";
                }

                m_bCapIsNoError = true;

            }
        }
    }
}

void CapPacket::calCompositeError()
{
    struct pcap_pkthdr *header;	// 数据包头
    const u_char *pkt_data;		// 数据包
    int packetSize;

    u_char buff[ETH_BUFFER_LENGTH] = {0};

    int iData_Start = 0;			// 数据位起始位
    int iSmpCnt_Start = 0;			// SmpCount起始位
    int iSmpCnt = 0;				// SmpCount值
    double iShuZiLiang = 0;			// 数字量

    static int m_iTestedPoints = 0;

    static double maxInChannel = 0;

    /*
     * CYPL
     * m_iASDU_Cnt
     * m_iFirstSmpCnt_Start
     * m_iASDU_Length
     * m_iSmpCnt_Length
     *
     */

    if( (m_iSmpRate = CYPL/50) == 0)
    {
        qDebug()<<"CapPacket:SmpRate error";
        return;
    }

    if(m_bInitCapPara) // if the interface is opened properly
    {
        int pcapCode = pcap_next_ex(m_fp, &header, &pkt_data);

        if (pcapCode > 0) {

            packetSize = header->caplen;

            if (packetSize > ETH_BUFFER_LENGTH)
            {
                    packetSize = ETH_BUFFER_LENGTH;
            }

            memcpy(buff, pkt_data, packetSize);
        }
        else
        {
            qDebug()<< " cap packet error!";
            return;
        }

        if(packetSize > 0)
        {
            for(int j = 0; j < m_iASDU_Cnt; j++)
            {
                if(m_bStopCap) return;

                iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);

                for(int i = 0; i < m_iSmpCnt_Length; i++)
                {
                    iSmpCnt += (buff[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                }

                if(iSmpCnt == 0)
                {
                    m_iTestedPoints = 0;

                    emit compositeArrayIsReady(); // do caculation at the begin of next second

//                    qDebug()<<"CapPacket: reset samplesIsReady_c, smpCnt="<<iSmpCnt;
                }

//                qDebug()<<"iSmpCnt:"<<iSmpCnt;

                m_Sync = buff[m_iSync_Start];

                for (int k = 0; k < 12 ; k++)
                {
                    int realChannel = j * 12 + k;

                    if(realChannel > m_iTongDaoCount)
                    {
                        realChannel = m_iTongDaoCount;
                    }

                    iShuZiLiang = 0;

                    iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * k;

                    for(int i = 0; i < m_iData_Length; i++) // rebuild the data to int according to m_iData_Length
                    {
                        iShuZiLiang += ( buff[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                    }

                    iShuZiLiang = ( iShuZiLiang /  1000.0 + 0.0000000001) / stdCurrent_compositeError; //to sure iShuZiLinag is not 0

                    if(realChannel == m_iTongDao)
                    {
                        //qDebug()<<"smvSamples:"<<m_iTestedPoints<<iSmpCnt<<iShuZiLiang; //WAR: chuncked when show in cmdline

                        m_tempArray[realChannel][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                    }

                    if(m_bStopCap) return;		// 外部停止接口
                }

                if(m_iTestedPoints < 10 * m_iSmpRate - 1) // do drawing every ten cycles
                {
                    m_iTestedPoints++;
                }
                else if(m_iTestedPoints == 10 * m_iSmpRate - 1)
                {
                    m_iTestedPoints++;
                    memcpy(m_PointArray ,m_tempArray, sizeof(m_PointArray));
                }
            }
        }
    }
}

void CapPacket::dft_14(double *samples,int M,int dft_N,int fs)   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
{
    int peak,n,k;
    double magic;
    double y,y2,maxu;

    int f0=50;
    long k0;

    double windowed_samples[dft_N];
    memset(windowed_samples,0,dft_N);

    for(n=0;n<dft_N;n++)
    {
        windowed_samples[n]=samples[n] *(0.3125-0.46875*std::cos(2*PI*n/dft_N)+0.1875*std::cos(4*PI*n/dft_N)-0.03125*std::cos(6*PI*n/dft_N));//FDMS_1 Window
    }

    int maxK=14;

    double Imag[maxK];
    double Real[maxK];
    for(k = 0;k < maxK;k++)
    {
        Imag[k]=0;
        Real[k]=0;

        for(n=0;n<dft_N;n++)
        {
            Real[k] = Real[k] + windowed_samples[n] * std::cos(2*PI*k*n/dft_N);
            Imag[k] = Imag[k] + windowed_samples[n] * std::sin(2*PI*k*n/dft_N);
        }
    }

    double abs[maxK];
    for(k=0;k<maxK;k++)
    {
        abs[k]=std::sqrt(Imag[k]*Imag[k]+Real[k]*Real[k]);
    }

    k0=std::ceil(f0*M*dft_N/fs);
    maxu=abs[k0];

    peak=k0;

    for(k=k0-3;k<k0+3;k++)
    {
        if(maxu<abs[k])
        {
            maxu=abs[k];//first high of freq spectrum
            peak=k;
        }
    }

    if(abs[peak-1] > abs[peak+1])  peak = peak - 1;

    y=abs[peak];
    y2=abs[peak+1];

    magic = 3.5*(y2-y)/(y2+y);

    freq_tmp = (peak+magic+0.5)*fs/dft_N;//freq of signal

    rms_tmp = (y+y2)*(3.43612+0.85434*std::pow(magic,2)+0.11871*std::pow(magic,4))/dft_N/1.4142135623;

    if(Real[peak]>0)
        phase_tmp=std::acos(Imag[peak]/abs[peak])-(magic+0.5)*PI;//phase of angel,range of angel is 0-2*PI
    else if(Real[peak]<0)
        phase_tmp=2*PI-std::acos(Imag[peak]/abs[peak])-(magic+0.5)*PI;
    else if(Real[peak]==0)
    {
        if(Imag[peak]>=0)   phase_tmp=-(magic+0.5)*PI;
        else    phase_tmp=PI-(magic+0.5)*PI;
    }

    if ((phase_tmp *= 180*60/PI) < 0) phase_tmp += 360*60;

    qDebug()<<"smv,dft_14:"<<rms_tmp<<phase_tmp<<freq_tmp;
}

//bool CapPacket::is_nonezero(int index, double sample_value, bool clear_buffer = false)
//{
//    static double tmp_buf[6][3];
//    static double last_count[6];

//    double count = 0;

//    if(clear_buffer)
//    {
//        memset(tmp_buf, 0x00, sizeof(tmp_buf));
//        memset(last_count, 0x00, sizeof(last_count));

//        return false;
//    }

//    count = tmp_buf[index][0] + tmp_buf[index][1] + tmp_buf[2] + sample_value;

//    if(count > 1)
//    {
//        return true;
//    }
//    else
//    {
//        return false;
//    }

//    tmp_buf[index][0] = tmp_buf[index][1];
//    tmp_buf[index][1] = tmp_buf[index][2];
//    tmp_buf[index][2] = sample_value;

//    last_count[index] = count;
//}

void CapPacket::CapSZBData()
{
    struct pcap_pkthdr *header;	// 数据包头
    const u_char *pkt_data;		// 数据包
    int packetSize;

    u_char buff[ETH_BUFFER_LENGTH] = {0};

    int iData_Start = 0;			// 数据位起始位
    int iSmpCnt_Start = 0;			// SmpCount起始位
    int iSmpCnt = 0;				// SmpCount值
    double iShuZiLiang = 0;			// 数字量

    /*
     * CYPL
     * m_iASDU_Cnt
     * m_iFirstSmpCnt_Start
     * m_iASDU_Length
     * m_iSmpCnt_Length
     *
     */

    if( (m_iSmpRate = CYPL/50) == 0)
    {
        qDebug()<<"CapPacket:SmpRate error";
        return;
    }

    if(m_bInitCapPara) // if the interface is opened properly
    {
        int pcapCode = pcap_next_ex(m_fp, &header, &pkt_data);

        if (pcapCode > 0) {

                packetSize = header->caplen;

                if (packetSize > ETH_BUFFER_LENGTH)
                {
                        packetSize = ETH_BUFFER_LENGTH;
                }

                memcpy(buff, pkt_data, packetSize);
        }
        else
        {
            //qDebug()<< " cap packet error!";
            return;
        }

        if(packetSize > 0)
        {
            for(int j = 0; j < m_iASDU_Cnt; j++)
            {
                if(m_bStopCap) return;

                iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);

                for(int i = 0; i < m_iSmpCnt_Length; i++)
                {
                    iSmpCnt += (buff[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                }

                double time_stamp = 0;

//                for(int i=0;i<4;i++)
//                     time_stamp += (buff[packetSize - i - 1] << (8 * i) );
//                time_stamp = (time_stamp * 40)/1000;

                unsigned int count = 0;
                for(int i = 0; i < 4; i++)
                    count += (unsigned int)buff[header->caplen - i - 1] << (8 * i);
                time_stamp = count * 4/ 100.0;

                if( time_stamp < 250 )
                {
                    time_stamp_mini = time_stamp;

                    m_iTestedPoints = 0;

                    memset(szb_found, 0x00, sizeof(szb_found));
                    memset(szb_delay, 0x00, sizeof(szb_delay));
                    memset(maxInChannel, 0x00, sizeof(maxInChannel));
                }

                m_Sync = buff[m_iSync_Start];

                for (int k = 0; k < m_iTongDatCountReal ; k++)
                {
                    iShuZiLiang = 0.00000000000001;

                    iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * k;

                    for(int i = 0; i < m_iData_Length; i++) // rebuild the data to int according to m_iData_Length
                    {
                        iShuZiLiang += (buff[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                    }

                    if(k == channelAll_mu[0]) // if phase a is not ready
                    {
                        double tmp = iShuZiLiang /maxValueMu[0];

                        //qDebug()<<"CapPacket: Ua, found samples "<<tmp<<channelAll_mu[0]<<time_stamp;

                        (*mu_sampleArray)[0][m_iTestedPoints] = tmp;// 存储绘图所需数字量数组

                        if( !szb_found[0])
                        {
                            if( tmp*tmp > 10)
                            {
                                szb_found[0] = true;
                                szb_delay[0] = time_stamp;
                            }
                        }

                        double tmp_double = fabs(tmp);

                        if(maxInChannel[0] < tmp_double ) maxInChannel[0] = tmp_double;
                    }

                    if(k == channelAll_mu[3])
                    {
                        double tmp = iShuZiLiang /10.0 /maxValueMu[3];

                        (*mu_sampleArray)[3][m_iTestedPoints] = tmp;// 存储绘图所需数字量数组

                        if( !szb_found[3])
                        {
                            if( tmp*tmp > 10)
                            {
                                szb_found[3] = true;
                                szb_delay[3] = time_stamp;
                            }
                        }
                        double tmp_double = fabs(tmp);

                        if(maxInChannel[3] < tmp_double ) maxInChannel[3] = tmp_double;
                    }

                    if(k == channelAll_mu[1]) // if phase b is not ready
                    {
                        double tmp = iShuZiLiang /maxValueMu[1];

                        //qDebug()<<"CapPacket: Ub, found samples ["<<iShuZiLiang<<"],       smpCnt="<<iSmpCnt;
                        (*mu_sampleArray)[1][m_iTestedPoints] = tmp;// 存储绘图所需数字量数组

                        if( !szb_found[1])
                        {
                            if( tmp*tmp > 10)
                            {
                                szb_found[1] = true;
                                szb_delay[1] = time_stamp;
                            }
                        }

                        double tmp_double = fabs(tmp);

                        if(maxInChannel[1] < tmp_double ) maxInChannel[1] = tmp_double;
                    }

                    if(k == channelAll_mu[4])
                    {
                        double tmp = iShuZiLiang /10.0 /maxValueMu[4];

                        (*mu_sampleArray)[4][m_iTestedPoints] = tmp;// 存储绘图所需数字量数组

                        if( !szb_found[4])
                        {
                            if( tmp*tmp > 10)
                            {
                                szb_found[4] = true;
                                szb_delay[4] = time_stamp;
                            }
                        }

                        double tmp_double = fabs(tmp);

                        if(maxInChannel[4] < tmp_double ) maxInChannel[4] = tmp_double;
                    }

                    if(k == channelAll_mu[2]) // if phase c is not ready
                    {
                        double tmp = iShuZiLiang /maxValueMu[2];

                        //qDebug()<<"CapPacket: Uc, found samples ["<<iShuZiLiang<<"],       smpCnt="<<iSmpCnt;
                        (*mu_sampleArray)[2][m_iTestedPoints] = tmp;// 存储绘图所需数字量数组

                        if( !szb_found[2])
                        {
                            if( tmp*tmp > 10)
                            {
                                szb_found[2] = true;
                                szb_delay[2] = time_stamp;
                            }
                        }

                        double tmp_double = fabs( tmp );

                        if(maxInChannel[2] < tmp_double ) maxInChannel[2] = tmp_double;
                    }

                    if(k == channelAll_mu[5])
                    {
                        double tmp = iShuZiLiang / 10.0 /maxValueMu[5];

                        (*mu_sampleArray)[5][m_iTestedPoints] = tmp;// 存储绘图所需数字量数组

                        if( !szb_found[5])
                        {
                            if( tmp*tmp > 10)
                            {
                                szb_found[5] = true;
                                szb_delay[5] = time_stamp;
                            }
                        }

                        double tmp_double = fabs(tmp);

                        if(maxInChannel[5] < tmp_double ) maxInChannel[5] = tmp_double;
                    }

                    if(m_bStopCap) return;		// 外部停止接口
                }

                if(m_iTestedPoints < 10 * m_iSmpRate - 1) // 采 10 个周期
                {
                    m_iTestedPoints++;
                }
                else if(m_iTestedPoints == 10 * m_iSmpRate - 1)
                {
                    if(mu_sampleArray == &mu_PointArray1)
                    {
                        mu_sampleArray = &mu_PointArray2;
                        mu_showArray = &mu_PointArray1;
                    }
                    else
                    {
                        mu_sampleArray = &mu_PointArray1;
                        mu_showArray = &mu_PointArray2;
                    }

                    bool szb_is_found = szb_found[0] || szb_found[1] || szb_found[2];

                    szb_is_found = szb_is_found || szb_found[3] || szb_found[4] || szb_found[5];

                    if(szb_is_found)
                    {
                        m_bStopCap = true;
                        emit szbDone();
                    }
                }

                m_bCapIsNoError = true;
            }
        }
    }
}
